/**内容文本处理*/
function addContentBtn() {
    const tar = $("#thread_content");
    const real = tar.height();
    tar.addClass('hide');
    const hide = tar.height();
    tar.removeClass('hide');
    if (real > hide) {
        const btn = $("#thread_content_show");
        btn.show();
        btn.click(() => {
            if (tar.hasClass("hide")) {
                tar.removeClass("hide");
                btn.text("收起");
            } else {
                tar.addClass("hide");
                btn.text("展开");
            }
        });
    }
}

function __errorHandle(err) {
    alert(JSON.stringify(err));
}

async function like(tar, aTar, commitID) {
    if (!commitID) {
        //like thread
        tar = $(tar);
        let nowLike = tar.hasClass('liked');
        let r = await $.get('/threads/like', { type: 'thread', tid: id, mode: nowLike ? 'cancel' : 'like' });
        if (r.success) {
            if (r.result) {
                tar[nowLike ? 'removeClass' : 'addClass']('liked');
                aTar.text(parseInt(aTar.text()) + (nowLike ? -1 : 1));
            }
        } else alert(r.err);
    }
}

function share(btn) {
    let url = `${location.origin}/t/${id}`;
    btn = $(btn);
    let offset = btn.offset();
    let text = $("<div>").text(url).addClass('share').css('top', offset.top + btn.outerHeight()).appendTo($('body'));
    let pos = offset.left - text.outerWidth() + btn.outerWidth();
    text.animate({ left: `${pos*0.9}px` }, 350).animate({ left: `+=${pos*.1}px` }, 100);
    $('body').bind('mousedown', e => e.target !== text[0] && (text.remove(), $('body').unbind(e)));

    let input = document.createElement('input');
    input.setAttribute('readonly', 'readonly');
    input.setAttribute('value', url);
    document.body.appendChild(input);
    input.select();
    input.setSelectionRange(0, 9999);
    text.css('color', document.execCommand('Copy') ? 'green' : 'red');
    document.body.removeChild(input);
}

function getTags() {
    $.get(`/threads/tags?tid=${id}`, r => {
        if (r && r.success) {
            let tar = $("#thread_tags").html('');
            r.result.forEach(e => {
                e = toRealName(e);
                tar.append(`<span class="capsule small"title="${e.id} - ${new Date(e.quote).toLocaleString()}">#${e.name}</span>`)
            })
        }
    });
}

let threadUserInfo;

function getUserInfo(uid) {
    $.get(`/user/getUserInfo/${uid}`, r => {
        if (r && r.success) {
            threadUserInfo = r = r.result;
            $("#user_name").html(r.nick || r.name);
        } else errorHandle('无法获取用户信息', r.err);
    });
    $.get('/img/user?uid=' + uid, (r, s, x) => {
        let type = (x.getResponseHeader('Content-Type') || "").trim().toLowerCase();
        if (type === 'text/plain') {
            $("#head_sculpture").replaceWith(`<svg class="icon"id="head_sculpture"aria-hidden="true"><use xlink:href="#icon-${r}"></use></svg>`);
        } else {
            $("#head_sculpture").attr('src', r);
        }
    });

}
let threadInfo;

function getThread() {
    console.log(id);
    $.ajax({
        url: `/threads/get?tid=${id}`,
        error: __errorHandle,
        success: (responseJSON) => {
            if (responseJSON.success) {
                let r = toRealName(responseJSON.result);
                if (!r) {
                    $("#thread_title").html('');
                    $("#thread_content").html(`${icon('error','red','5vw')}<span class="title">找不到帖子</span>`);
                    return;
                }
                threadInfo = r;
                $("#thread_title").html(r.title);
                $("#thread_content").html(marked(r.content));
                $("#thread_modify").html(new Date(r.editTime).toLocaleString());
                $("#threads_time").html(new Date(r.releaseTime).toLocaleString());
                if (r.hasLike) $("#thread_love_box").addClass('liked');
                $("#thread_love_amount").text(r.like || 0);
                getUserInfo(r.uid);
                login_check(s => (s && userInfo.info.uid == r.uid || userHasPermission('edit_other_thread')) && $("#editor").show());
            } else {
                $("#thread_content").html("获取帖子时出错: <br>" + responseJSON.err);
            }
        }
    });
}

const id = (() => {
    let y = getQueryVariable('tid');
    let x = parseInt(y);
    console.log(y, x);
    return isNaN(x) ? y : x;
})();

$(addContentBtn);
$(getThread);
$(getTags);